package com.namecard.namecardapi.controller;

import io.swagger.annotations.Api;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.request.AuthTwitterRequest;
import me.zhyd.oauth.utils.AuthStateUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
@RequestMapping("/oauth")
@Api(tags = "JustAuth用户登录接口")
public class RestAuthController {
    
    @Value("${twitter.clientid}")
    private String clientId;
    @Value("${twitter.clientsecret}")
    private String clientSecret;
    @Value("${twitter.callbackurl}")
    private String callbackUrl;

    @RequestMapping("/render")
    public void renderAuth(HttpServletResponse response) throws IOException {
        AuthRequest authRequest = getAuthRequest();
        response.sendRedirect(authRequest.authorize(AuthStateUtils.createState()));
    }

    @RequestMapping("/callback")
    public Object login(AuthCallback callback) {
        AuthRequest authRequest = getAuthRequest();
        return authRequest.login(callback);
    }

    private AuthRequest getAuthRequest() {
        // 国外平台 目前必须要手动配置代理
        System.setProperty("proxyPort", "443");
        System.setProperty("proxyHost", "127.0.0.1");
        return new AuthTwitterRequest(AuthConfig.builder()
                .clientId(clientId)
                .clientSecret(clientSecret)
                .redirectUri(callbackUrl)
                .build());
    }
}